import json
import re
import shutil
import traceback

import win32con

from Config import Params
from Utils import DirUtil
from Utils.TimeUtil import *
import os,math
import win32clipboard as w

from Service.MyLogger import MyLogger
import os,logging
logFileName =  os.path.basename(__file__).split(".")[0]
from Statistics.COMMON import commonLogger
log = commonLogger # MyLogger(r"./Logs/%s.log" % (logFileName), logging.DEBUG, logging.DEBUG)
def uniqueArr(aa):
    naa = []
    for ee in aa:
        if ee not in naa:
            naa.append(ee)
    return naa


def arr2Str(aa,withQuote=""):
    return ','.join([withQuote+str(ee)+withQuote for ee in aa])
def stampArr2timeArr(aa):
    return [stampS2TimeStr(int(ee)) for ee in aa]

def file2Str(path):
    foo = open(path,"r",encoding='utf-8',errors='ignore')
    ss = foo.read()
    foo.close()
    return ss
def getNewFilePathAddingSuff(path:str, suff:str):
    filePathName,ext = os.path.splitext(path)
    filePathNameExt = filePathName + suff + ext
    print("yzprt filePathNameExt:", filePathNameExt)
    return filePathNameExt
def popFirstRow(path:str):
    aa = file2Arr(path)
    while len(aa)>0:
        poped = aa.pop(0)
        if poped is not None and poped.replace(' ','').replace('\t','') != "":
            arr2File(aa,path)
            return poped
    return None
def get1RowContaingContent(path:str, rowContent,isPop=False):
    aa = file2Arr(path)
    poped = None
    for i in range(len(aa)):
        print("yzprt aa[%s] vs rowContent:"%(i), aa[i],"vs",rowContent)
        if aa[i].find(rowContent)>=0:
            if isPop:
                poped = aa.pop(i)
            else:
                poped = aa[i]
            arr2File(aa,path)
            return poped
    return None
def getOuterIndAndAdd():
    try:
        with open(os.path.join(Params.ROOT_DIR, "./raw/outerInd.txt"), "r", encoding="utf-8", errors="ignore") as f:
            ind = f.read()
        ind = int(ind)
    except:
        log.error("yzlog traceback.format_exc():", traceback.format_exc())
        ind = 0
        with open(os.path.join(Params.ROOT_DIR, "./raw/outerInd.txt"), "w", encoding="utf-8", errors="ignore") as f:
            f.write(str(ind))
    with open(os.path.join(Params.ROOT_DIR,"./raw/outerInd.txt"),"w",encoding="utf-8",errors="ignore") as f:
        f.write(str(ind+1))
    print("yzprt outerInd:", ind)
    return ind



def append1Row(path:str, content:str):
    foo = open(path, "a", encoding='utf-8', errors='ignore')
    foo.write('\n'+content)
    foo.close()


def file2Arr(path):
    foo = open(path,"r",encoding='utf-8',errors='ignore')
    aa = foo.read().strip('\n').split('\n')
    foo.close()
    return aa
def file2ArrArr(path):
    foo = open(path, "r", encoding='utf-8', errors='ignore')
    aa = foo.readlines()
    foo.close()
    naa = []
    lenA0 = len(aa[0].split('\t'))
    for ee in aa:
        ee = ee.strip('\n')
        if ee is None or ee.strip(' ') == '' or len(ee) < 10:
            print("yzprt ee4:", ee)
            continue
        nee = ee.split('\t')
        while len(nee) < lenA0:
            nee.append(None)
        naa.append(nee)
    return naa
def kill1RowOfFile(path:str,rowInd=0):
    arr = file2Arr(path)
    if len(arr)>=rowInd:
        arr.pop(rowInd)
    arr2File(arr,path)
def arr2File(aa,path):
    foo = open(path, "w", encoding='utf-8', errors='ignore')
    foo.write('\n'.join(aa))
    foo.close()
def splitFileByOnes(path,n):
    aa = file2Arr(path)
    batchCount = math.ceil(len(aa)/n)
    dir,fileName = os.path.split(path)
    pureFileName,ext = os.path.splitext(fileName)
    # log.info(dir,fileName,pureFileName,ext)
    # log.info(len(aa),n,batchCount)
    nDir = os.path.join(dir,pureFileName+"splitOnes_"+str(n))
    pass #2204# print(nDir)
    if not os.path.exists(nDir):
        os.makedirs(nDir)
    else:
        pass #2204# print("Dir existed:",nDir)
    for i in range(n):
        arr2File(aa[i*batchCount:i*batchCount+batchCount],os.path.join(nDir,pureFileName+"_"+str(i+1)+ext))
        pass #2204# print("successByOnes:", i + 1, "/", n)
def splitFileByRows(path,rows):
    aa = file2Arr(path)
    batchCount = rows
    n = math.ceil(len(aa) / rows)
    dir, fileName = os.path.split(path)
    pureFileName, ext = os.path.splitext(fileName)
    # log.info(dir, fileName, pureFileName, ext)
    # log.info(len(aa), n, batchCount)
    nDir = os.path.join(dir, pureFileName + "splitRows_" + str(batchCount))
    pass #2204# print(nDir)
    if not os.path.exists(nDir):
        os.makedirs(nDir)
    else:
        pass #2204# print("Dir existed:", nDir)
    for i in range(n):
        arr2File(aa[i * batchCount:i * batchCount + batchCount],os.path.join(nDir, pureFileName + "_" + str(i + 1) + ext))
        pass #2204# print("successByRows:",i+1,"/",n)
def file2sqlArr(path):
    foo = open(path,"r",encoding='utf-8',errors='ignore')
    aa = foo.readlines()
    foo.close()
    naa = []
    for ee in aa:
        nee = ee.replace('\n','').strip(' ')
        if nee != "" and nee.find("--")<0:
            naa.append(nee)
            # mylog.info(nee)
    return naa
def saveToTxt(insertArr):
    redisDir = r"D:\\redis同步到sql\\同步8时间_" + str(time.strftime("%Y-%m-%d_%H%M%S", time.localtime())) + ".txt"
    foo = open(redisDir, "a")
    for i in range(len(insertArr)):
        foo.write("\t".join(str(ee) for ee in insertArr[i]) + '\n')
        # mylog.info("\t".join(str(ee) for ee in insertArr[i])+'\n')
    foo.close()
def printArr(aa,isWithCount=False):
    for ee in aa:
        print(ee)
    if isWithCount:
        print("len(aa):",len(aa))
def printDict(dictt,isWithCount=False,isWithInd=False):
    ind=0
    for k,v in dictt.items():
        if isWithInd:
            ind += 1
            pass #2204# print(ind,k,v)
        else:
            pass #2204# print(k,v)
    if isWithCount:
        pass #2204# print("len(dictt):",len(dictt))
def get_text():
    w.OpenClipboard()
    d = w.GetClipboardData(win32con.CF_UNICODETEXT)
    w.CloseClipboard()
    return d

def set_text(aString):
    w.OpenClipboard()
    w.EmptyClipboard()
    try:
        w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
    except:
        w.SetClipboardData(win32con.CF_UNICODETEXT, '"'+aString+'"')
        pass #2204# print("print as "+'"'+aString+'"')
    w.CloseClipboard()

def mergeList2Dict(kList:list,vList:list):
    if kList is None or len(kList)<1 or len(kList) != len(vList):
        return {}
    dictt = {}
    for i in range(len(kList)):
        dictt.update({kList[i]:vList[i]})
    return dictt

def copyFile2Dir(srcfile,dstpath):                       # 复制函数
    if not os.path.isfile(srcfile):
        print ("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.copy(srcfile, os.path.join(dstpath, fname))          # 复制文件
        print ("copy %s -> %s"%(srcfile, os.path.join(dstpath, fname)))
def moveFile2Dir(srcfile,dstpath):                       # 移动函数
    if not os.path.isfile(srcfile):
        print ("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.move(srcfile, os.path.join(dstpath, fname))          # 移动文件
        print ("move %s -> %s"%(srcfile, os.path.join(dstpath, fname)))
def makeDirIfNotExists(dir):
    if os.path.exists(dir):
        os.makedirs(dir)
def getDbConnByFile(filePath:str):
    with open(filePath,"r",encoding='utf-8',errors='ignore') as f:
        ss = f.read()
    ss = ss.replace("\n","").replace(" ","").replace("}","}**").strip("**")
    arr = re.split("\*\*",ss)
    dictt = {}
    for i in range(len(arr)):
        k,v = arr[i].split("=")
        dictt[k]=v
    dictt["rsConn"] = dictt["rsConn"].replace("sqlConn",dictt["sqlConn"])
    dictt["rsConn"] = dictt["rsConn"].replace("rdsConn", dictt["rdsConn"])
    dictt["dbConnect"] = dictt["dbConnect"].replace("rsConn", dictt["rsConn"])
    dictt["dbConnect"] = dictt["dbConnect"].replace("dbXX", dictt["dbXX"])
    for k,v in dictt.items():
        dictt[k] = json.loads(v)
    print('dictt["dbConnect"]:',dictt["dbConnect"])
    dbConn = dictt["dbConnect"]
    return dbConn
if __name__ == '__main__':
    pass
    set_text("123")
    # splitFileByOnes(r"C:\Users\Xab\Desktop\slowLog05181555\littlepigapp01-new-slow.log",6)
    # splitFileByRows(r"C:\Users\Xab\Desktop\slowLog05181555\littlepigapp01-new-slow.log",1146559)
    # srcFile = r"C:/Users/ADMIN/Desktop/Caches视频处理/Richard Clayderman - Souvenirs d'enfance (爱的纪念).mkv"
    # dstPath = r'C:/Users/ADMIN/Desktop/Caches视频处理/已发布'
    # moveFile2Dir(srcFile,dstPath)
    # print(os.path.join(dstPath,"已发布2","a.mp4")) # 是可以直接连接3个的